import { ModalForm, ProForm, ProFormCaptcha, StepsForm } from '@/components/Pro';
import { authControllerSendSmsCode } from '@/services/auth/auth';
import {
  deviceCtrlControllerImplExecuteGridCtrl,
  deviceCtrlControllerImplGetGridCtrl,
  deviceCtrlControllerImplGetProgress,
} from '@/services/ess/deviceCtrls';
import { sysUserControllerGetUserRealPhone } from '@/services/ess/sysUser';
import { MailTwoTone } from '@ant-design/icons';
import { Button, Flex, message, Modal, Popover, Radio, Spin, Tag, Typography } from 'antd';
import CryptoJS from 'crypto-js/crypto-js';
import JSEncrypt from 'jsencrypt';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl, useModel } from 'umi';
import { AESKey, RESKey } from '../encryptKey';
import styles from '../index.less';

const { Text } = Typography;

// 添加状态类型定义
type CtrlStatus = {
  result: number | null;
  ctrlCmd: number;
  taskStatus?: number;
  step?: number;
  percent?: number;
  resultDesc?: string;
  errorMsg?: string;
  progresses?: Progress[];
  isTaskFinished?: boolean;
};

// 添加控制命令常量
const GRID_CONTROL_COMMANDS = {
  GRID_TO_OFF_GRID_PRESET: 1, // 并网转离网预设置
  GRID_TO_OFF_GRID: 2, // 并网转离网
  OFF_GRID_TO_GRID_PRESET: 3, // 离网转并网预设置
  OFF_GRID_TO_GRID: 4, // 离网转并网
  RUN_OFF_GRID_STRATEGY: 5, // 运行离网策略
  RUN_GRID_STRATEGY: 6, // 运行并网策略
} as const;

// 添加进度类型定义
type Progress = {
  status: number;
  step: number;
  resultDesc: string;
};

// 添加状态描述映射
const STATUS_DESCRIPTIONS: Record<string, string> = {
  启动并网策略: '正在切换到并网模式...',
  启动离网策略: '正在切换到离网模式...',
  并网转离网预设置: '正在执行并网转离网预设置...',
  离网转并网预设置: '正在执行离网转并网预设置...',
  并网转离网: '正在执行并网转离网...',
  离网转并网: '正在执行离网转并网...',
};

const GridSwitch: React.FC = () => {
  const [isFirst, setIsFirst] = useState(false);
  const [gridCurrentMode, setGridCurrentMode] = React.useState<'true' | 'false'>('true');
  const [gridMode, setGridMode] = React.useState<'grid' | 'offGrid'>('grid');
  const [loading, setLoading] = React.useState(false);
  const [smsModalVisible, setSmsModalVisible] = useState(false);
  const [isCaptchaReady, setIsCaptchaReady] = useState(false);
  const [userPhone, setUserPhone] = useState<string | null>(null);
  const [pendingCtrlCmd, setPendingCtrlCmd] = useState<number | null>(null);
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();

  // 轮询间隔时间（毫秒）
  const POLL_INTERVAL = 3000;

  // 初始化
  const keyPair = new JSEncrypt();

  // 添加控制状态
  const [ctrlStatus, setCtrlStatus] = useState<CtrlStatus | null>(null);

  // 添加 StepsForm 的 form 实例引用
  const [stepFormRef] = useState<any>();

  // 在组件内添加新的状态
  const [currentStep, setCurrentStep] = useState(0);

  // 创建函数引用
  const handleStepFinishRef = useRef<any>(null);
  const pollExecutionStatusRef = useRef<any>(null);
  const executeControlRef = useRef<any>(null);

  /**
   * AES加密
   * @param content
   * @returns {string}
   * @constructor
   */
  const AESEncryption = (content: string) => {
    const aesContent = CryptoJS.enc.Utf8.parse(content);
    const key = CryptoJS.enc.Utf8.parse(AESKey.key);
    const iv = CryptoJS.enc.Utf8.parse(AESKey.iv);
    const encrypted = CryptoJS.AES.encrypt(aesContent, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
  };

  /**
   *RSA加密
   * @returns
   */
  const encryptByRsa = (content: string) => {
    keyPair.setPublicKey(RESKey);
    return keyPair.encrypt(AESEncryption(content));
  };

  // 添加状态描述处理函数
  const getStatusDescription = (resultDesc: string | undefined, status: number | undefined) => {
    if (!resultDesc) return '等待开始执行';

    // 如果状态为1(完成)，显示完成状态
    if (status === 1) {
      if (resultDesc === '启动并网策略') {
        return '已切换到并网模式';
      }
      if (resultDesc === '启动离网策略') {
        return '已切换到离网模式';
      }
      if (resultDesc.includes('预设置')) {
        return resultDesc.replace('预设置', '预设置已完成');
      }
      if (resultDesc === '并网转离网') {
        return '并网转离网已完成';
      }
      if (resultDesc === '离网转并网') {
        return '离网转并网已完成';
      }
      return `${resultDesc}已完成`;
    }

    // 如果状态不为1，显示进行中状态
    return STATUS_DESCRIPTIONS[resultDesc] || resultDesc;
  };

  // 添加进度查询函数
  const queryProgress = async () => {
    try {
      const response = await deviceCtrlControllerImplGetProgress();
      if (response.success && response.data) {
        setCtrlStatus((prevStatus) => ({
          ...prevStatus!,
          step: response?.data?.step,
          percent: response?.data?.percent,
          resultDesc: getStatusDescription(response?.data?.resultDesc, response?.data?.status),
          progresses: response?.data?.progresses?.map((progress) => ({
            ...progress,
            resultDesc: getStatusDescription(progress.resultDesc, progress.status),
          })),
        }));
      }
    } catch (error) {
      console.error('查询进度失败:', error);
    }
  };

  // 获取用户手机号
  const fetchUserRealPhone = async (): Promise<string | false> => {
    try {
      const userId = initialState?.userId;
      const stationId = initialState?.stationId;

      if (!userId) {
        throw new Error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserId' }));
      }

      const headers: Record<string, string> = {};
      if (stationId) {
        headers['Station-Id'] = stationId.toString();
      }

      const response = await sysUserControllerGetUserRealPhone({ userId }, { headers });

      if (response.success && response.data) {
        const encryptedPhone = encryptByRsa(response.data);
        if (encryptedPhone) {
          setUserPhone(encryptedPhone);
          return encryptedPhone; // 返回加密后的手机号
        }
        throw new Error('手机号加密失败');
      } else {
        throw new Error(
          response.message ||
            intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }),
        );
        return false;
      }
    } catch (error) {
      console.error('获取用户手机号失败:', error);
      throw error;
    }
  };

  // 获取验证码
  const handleGetCaptcha = async () => {
    // 开发环境下直接返回成功
    if (process.env.NODE_ENV === 'development') {
      message.success('验证码已发送: 666666');
      setIsCaptchaReady(true);
      return true;
    }

    try {
      let phoneNumber = userPhone;

      if (!phoneNumber) {
        // 如果没有手机号，先获取手机号
        phoneNumber = await fetchUserRealPhone();
      }

      if (!phoneNumber) {
        throw new Error(intl.formatMessage({ id: 'strategyAction.error.unableToGetUserPhone' }));
      }

      const stationId = initialState?.stationId;
      const headers: Record<string, string> = {};
      if (stationId) {
        headers['Station-Id'] = stationId.toString();
      }

      // 如果没有手机号，先获取手机号
      if (!userPhone) {
        const phone = await fetchUserRealPhone();
        if (!phone) {
          setLoading(false);
          return;
        }
      }

      // 发送验证码
      const response = await authControllerSendSmsCode(
        {
          mobile: phoneNumber,
          smsType: 'issuance_strategy',
        },
        { headers },
      );

      if (response.success) {
        message.success(
          intl.formatMessage({ id: 'strategyAction.error.verificationCodeSentSuccessfully' }),
        );
        setIsCaptchaReady(true);
        return true;
      } else {
        throw new Error(
          response.message ||
            intl.formatMessage({ id: 'strategyAction.error.verificationCodeSendFailed' }),
        );
      }
    } catch (error) {
      // const errorMessage = error instanceof Error ? error.message : '发送验证码失败';
      // message.error(errorMessage);
      setIsCaptchaReady(false);
      return false;
    }
  };

  // 修改重置状态的函数
  const resetState = async (isCompletion: boolean = false) => {
    return new Promise<void>((resolve) => {
      setLoading(true);

      setTimeout(async () => {
        try {
          // 获取最新的并网状态
          const response = await deviceCtrlControllerImplGetGridCtrl();

          if (response.success && response.data) {
            const isGridConnected = response.data?.gridConnected;

            await Promise.all([
              // 更新并网状态
              new Promise<void>((resolveState) => {
                if (isCompletion) {
                  // 完成操作时，更新为最新状态
                  setGridCurrentMode(isGridConnected ? 'true' : 'false');
                }
                // 重新开始时保持原状态
                resolveState();
              }),
              // 更新切换模式
              new Promise<void>((resolveState) => {
                if (isCompletion) {
                  // 完成操作时，根据最新状态设置切换模式
                  setGridMode(isGridConnected ? 'grid' : 'offGrid');
                }
                // 重新开始时保持原模式
                resolveState();
              }),
              // 更新控制状态
              new Promise<void>((resolveState) => {
                setCtrlStatus({
                  result: null,
                  ctrlCmd: 0,
                  taskStatus: undefined,
                  step: 0,
                  errorMsg: undefined,
                  // 使用当前状态而不是 API 返回的状态来设置提示信息
                  resultDesc: isCompletion
                    ? isGridConnected
                      ? '请进行并网转离网预设置'
                      : '请进行离网转并网预设置'
                    : gridCurrentMode === 'true'
                    ? '请进行并网转离网预设置'
                    : '请进行离网转并网预设置',
                });
                resolveState();
              }),
            ]);
          }

          // 重置其他状态
          await Promise.all([
            new Promise<void>((resolveState) => {
              setCurrentStep(0);
              resolveState();
            }),
            new Promise<void>((resolveState) => {
              setPendingCtrlCmd(null);
              resolveState();
            }),
            new Promise<void>((resolveState) => {
              setSmsModalVisible(false);
              resolveState();
            }),
            new Promise<void>((resolveState) => {
              setIsCaptchaReady(false);
              resolveState();
            }),
          ]);

          setLoading(false);
          resolve();
        } catch (error) {
          console.error('重置状态失败:', error);
          message.error('重置状态失败，请刷新页面重试');
          setLoading(false);
          resolve();
        }
      }, 1000);
    });
  };

  const initGridState = async () => {
    try {
      const response = await deviceCtrlControllerImplGetGridCtrl();

      if (!response.data) {
        return;
      }

      const isGridConnected = response.data?.gridConnected;
      setGridCurrentMode(isGridConnected ? 'true' : 'false');
      setGridMode(isGridConnected ? 'grid' : 'offGrid');

      // 如果有 taskStatus，先查询进度
      let progressData;
      if (response.data.taskStatus !== undefined) {
        const progressResponse = await deviceCtrlControllerImplGetProgress();
        progressData = progressResponse.data;
      }

      // 设置初始状态描述
      let initialResultDesc = isGridConnected ? '请进行并网转离网预设置' : '请进行离网转并网预设置';

      // 根据任务状态和控制命令确定最终的状态描述
      if (response.data.taskStatus === 1) {
        // 任务完成的情况
        if (response.data.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET) {
          initialResultDesc = '并网转离网预设置已完成';
          setCurrentStep(1);
        } else if (response.data.ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET) {
          initialResultDesc = '离网转并网预设置已完成';
          setCurrentStep(1);
        } else if (response.data.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID) {
          // 检查是否所有进度都已完成
          const allProgressesCompleted =
            progressData?.progresses?.every((p) => p.status === 1) ?? false;
          if (allProgressesCompleted) {
            initialResultDesc = '并网转离网已完成，请执行运行离网策略';
            setCurrentStep(2);
          } else {
            initialResultDesc = progressData?.resultDesc || '正在执行并网转离网';
            setCurrentStep(1);
          }
        } else if (response.data.ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID) {
          const allProgressesCompleted =
            progressData?.progresses?.every((p) => p.status === 1) ?? false;
          if (allProgressesCompleted) {
            initialResultDesc = '离网转并网已完成，请执行运行并网策略';
            setCurrentStep(2);
          } else {
            initialResultDesc = progressData?.resultDesc || '正在执行离网转并网';
            setCurrentStep(1);
          }
        } else if (
          response.data.ctrlCmd === GRID_CONTROL_COMMANDS.RUN_GRID_STRATEGY ||
          response.data.ctrlCmd === GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY
        ) {
          // 只有执行完运行策略才算真正完成
          initialResultDesc = isGridConnected ? '请进行并网转离网预设置' : '请进行离网转并网预设置';
          setCurrentStep(0);
        }
      } else if (response.data.taskStatus === 2 || response.data.taskStatus === 3) {
        // 任务执行中或等待中的情况
        if (progressData?.resultDesc) {
          if (
            progressData.resultDesc === '启动并网策略' ||
            progressData.resultDesc === '启动离网策略'
          ) {
            initialResultDesc = '等待开始执行';
          } else {
            initialResultDesc =
              STATUS_DESCRIPTIONS[progressData.resultDesc] || progressData.resultDesc;
          }
        }
        setLoading(true);
        pollExecutionStatusRef.current(false);
      } else {
        setCurrentStep(0);
      }

      // 设置控制状态
      const newStatus = {
        result: response.data.result ?? null,
        ctrlCmd: response.data.ctrlCmd || 0,
        taskStatus: response.data.taskStatus,
        errorMsg: response.data.errorMsg,
        isTaskFinished: response.data.isTaskFinished,
        step: progressData?.step,
        percent: progressData?.percent,
        resultDesc: initialResultDesc,
        progresses: progressData?.progresses?.map((progress) => ({
          ...progress,
          resultDesc:
            progress.resultDesc === '启动并网策略' || progress.resultDesc === '启动离网策略'
              ? '等待开始执行'
              : getStatusDescription(progress.resultDesc, progress.status),
        })),
      };

      setCtrlStatus(newStatus);

      // 检查是否存在错误状态,直接重置
      if (response.data.taskStatus === 0 || response.data.errorMsg) {
        await resetState();
        return;
      }
    } catch (error) {
      console.error('初始化状态失败:', error);
      message.error('初始化状态失败，请刷新页面重试');
      await resetState();
    }
  };

  useEffect(() => {
    if (!isFirst) {
      initGridState();
      setIsFirst(true);

      // 添加定时轮询
      const pollTimer = setInterval(async () => {
        if (!loading) {
          try {
            const response = await deviceCtrlControllerImplGetGridCtrl();
            if (response.data) {
              const newStatus = {
                result: response.data.result ?? null,
                ctrlCmd: response.data.ctrlCmd || 0,
                taskStatus: response.data.taskStatus,
                errorMsg: response.data.errorMsg,
              };
              setCtrlStatus(newStatus);

              // 如果有 taskStatus，查询进度
              if (response.data.taskStatus !== undefined) {
                await queryProgress();
              }

              // 如果任务完成，更新步骤
              if (response.data.taskStatus === 1) {
                const isGridConnected = response.data.gridConnected;
                if (isGridConnected) {
                  switch (response.data.ctrlCmd) {
                    case GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET:
                      setCurrentStep(1);
                      break;
                    case GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID:
                    case GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY:
                      setCurrentStep(2);
                      break;
                  }
                } else {
                  switch (response.data.ctrlCmd) {
                    case GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET:
                      setCurrentStep(1);
                      break;
                    case GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID:
                    case GRID_CONTROL_COMMANDS.RUN_GRID_STRATEGY:
                      setCurrentStep(2);
                      break;
                  }
                }
              }
            }
          } catch (error) {
            console.error('轮询状态失败:', error);
          }
        }
      }, POLL_INTERVAL);

      return () => clearInterval(pollTimer);
    }
  }, [isFirst, loading]);

  // 定义 executeControl
  executeControlRef.current = async (
    gridConnected: boolean,
    ctrlCmd: number,
    verificationCode?: string,
    shouldShowConfirm?: boolean,
  ) => {
    if (![1, 2, 3, 4, 5, 6].includes(ctrlCmd)) {
      message.error('无效的控制命令');
      return false;
    }

    // 执行前清空状态
    setCtrlStatus(null);
    setLoading(true);

    try {
      const response = await deviceCtrlControllerImplExecuteGridCtrl(
        {
          gridConnected,
          ctrlCmd,
        },
        {
          headers: {
            'Verification-Code': verificationCode,
          },
        },
      );

      if (response.success) {
        setSmsModalVisible(false);
        setIsCaptchaReady(false);
        setPendingCtrlCmd(null);
        return pollExecutionStatusRef.current(shouldShowConfirm);
      } else {
        setLoading(false);
        message.error(response.message || '执行失败');
        return false;
      }
    } catch (error) {
      setLoading(false);
      message.error('执行控制命令失败');
      return false;
    }
  };

  // 定义 pollExecutionStatus
  pollExecutionStatusRef.current = async (shouldShowConfirm?: boolean) => {
    try {
      const response = await deviceCtrlControllerImplGetGridCtrl();
      if (response.success && response.data) {
        const { errorMsg, ctrlCmd, taskStatus } = response.data;

        // 更新控制状态
        setCtrlStatus((prevStatus) => {
          // 如果状态没有改变，不更新
          if (
            prevStatus?.taskStatus === taskStatus &&
            prevStatus?.ctrlCmd === ctrlCmd &&
            prevStatus?.errorMsg === errorMsg
          ) {
            return prevStatus;
          }
          return {
            ctrlCmd: ctrlCmd || 0,
            taskStatus,
            errorMsg,
          };
        });

        // 如果有 taskStatus，查询进度
        if (taskStatus !== undefined) {
          queryProgress();
        }

        // 根据 taskStatus 处理不同状态
        if (taskStatus === -1) {
          // 未反馈，继续轮询
          setLoading(true);
          setTimeout(() => pollExecutionStatusRef.current(shouldShowConfirm), POLL_INTERVAL);
          return false;
        } else if (taskStatus === 0) {
          // 执行失败
          setLoading(false);
          message.error(errorMsg || '操作执行失败');
          return false;
        } else if (taskStatus === 1) {
          // 执行成功
          setLoading(false);

          // 检查是否已经显示过成功消息
          if (ctrlStatus?.taskStatus !== 1) {
            message.success('操作执行成功');
          }

          if (shouldShowConfirm) {
            if (gridMode === 'grid' && ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID) {
              Modal.confirm({
                title: '确认执行运行离网策略',
                content: '并网转离网已完成，是否立即执行运行离网策略？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY);
                },
              });
            } else if (
              gridMode === 'offGrid' &&
              ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID
            ) {
              Modal.confirm({
                title: '确认执行运行并网策略',
                content: '离网转并网已完成，是否立即执行运行并网策略？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.RUN_GRID_STRATEGY);
                },
              });
            }
          } else {
            // 只有在状态真正改变时才更新步骤
            if (ctrlStatus?.taskStatus !== 1) {
              setCurrentStep((prev) => prev + 1);
            }
          }
          return true;
        } else if (taskStatus === 2) {
          // 执行中
          setLoading(true);
          setTimeout(() => pollExecutionStatusRef.current(shouldShowConfirm), POLL_INTERVAL);
          return false;
        } else if (taskStatus === 3) {
          // 等待中
          setLoading(true);
          setTimeout(() => pollExecutionStatusRef.current(shouldShowConfirm), POLL_INTERVAL);
          return false;
        } else {
          setLoading(false);
          message.error(`未知的执行状态: ${taskStatus}`);
          return false;
        }
      }
      return false;
    } catch (error) {
      setLoading(false);
      message.error('查询执行状态失败');
      return false;
    }
  };

  // 定义 handleStepFinish
  handleStepFinishRef.current = async (ctrlCmd: number, shouldShowConfirm?: boolean) => {
    try {
      setPendingCtrlCmd(ctrlCmd);

      // 检查当前状态和操作是否匹配
      if (gridCurrentMode === 'true') {
        if (
          ![
            GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET,
            GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID,
            GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY,
          ].includes(ctrlCmd)
        ) {
          message.error('当前并网状态下不能执行该操作');
          return false;
        }
      } else {
        if (
          ![
            GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET,
            GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID,
            GRID_CONTROL_COMMANDS.RUN_GRID_STRATEGY,
          ].includes(ctrlCmd)
        ) {
          message.error('当前离网状态下不能执行该操作');
          return false;
        }
      }

      if (
        ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET ||
        ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET
      ) {
        setSmsModalVisible(true);
        return true;
      }

      return executeControlRef.current(
        gridCurrentMode === 'true',
        ctrlCmd,
        undefined,
        shouldShowConfirm,
      );
    } catch (error) {
      console.error('执行操作失败:', error);
      message.error('执行操作失败，请重试');
      return false;
    }
  };

  // 修改验证码提交处理函数
  const handleSmsVerify = async (values: { smsCode: string }) => {
    // 开发环境下跳过验证码检查
    if (process.env.NODE_ENV === 'development') {
      if (values.smsCode !== '666666') {
        message.error('验证码错误');
        return false;
      }
    } else {
      // 生产环境下的正常验证逻辑
      if (!isCaptchaReady) {
        message.error('请先获取验证码');
        return false;
      }
    }

    if (gridCurrentMode === null) {
      message.error('请确认并离网状态');
      return false;
    }

    if (pendingCtrlCmd === null) {
      message.error('无效的控制命令');
      return false;
    }

    const success = await executeControlRef.current(
      gridCurrentMode === 'true',
      pendingCtrlCmd,
      values.smsCode,
    );
    return success; // 直接返回 success 结果
  };

  const handleModeChange = (e: any) => {
    // 检查切换是否合法
    if (
      (gridCurrentMode === 'true' && e.target.value === 'offGrid') ||
      (gridCurrentMode === 'false' && e.target.value === 'grid')
    ) {
      message.error('当前状态不允许进行该切换操作');
      return;
    }

    setGridMode(e.target.value);
    setCtrlStatus(null);
    setCurrentStep(0);
    setLoading(false);
    setPendingCtrlCmd(null);
    setSmsModalVisible(false);
    setIsCaptchaReady(false);
  };

  // const handleCurrentModeChange = (e: any) => {
  //   setGridCurrentMode(e.target.value);
  // };

  const manualControlTip = (
    <div className={styles.gridSwitchTips}>
      {gridMode === 'grid' ? '手动断开并网点开关刀闸' : '手动闭合并网点开关刀闸'}
    </div>
  );

  // 修改状态显示组件
  const StatusDisplay = ({
    status,
    loading,
    step,
  }: {
    status: CtrlStatus | null;
    loading: boolean;
    step: number;
  }) => {
    // 根据当前步骤和状态生成状态描述
    const getStepStatusDescription = () => {
      if (!status) {
        return gridCurrentMode === 'true' ? '请进行并网转离网预设置' : '请进行离网转并网预设置';
      }

      // 如果有进度信息，优先显示进度信息
      if (status.progresses?.length > 0) {
        // 保持原有的进度显示逻辑
        const sortedProgresses = [...status.progresses].sort((a, b) => a.step - b.step);
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            <p>当前状态：</p>
            {sortedProgresses.map((progress, index) => {
              let statusType: 'success' | 'warning' | 'danger' | undefined = 'success';

              // 如果是"等待开始执行"，使用 undefined 显示默认颜色
              if (progress.resultDesc === '等待开始执行') {
                statusType = undefined;
              } else {
                switch (progress.status) {
                  case 0:
                    statusType = 'danger';
                    break;
                  default:
                    statusType = 'success';
                }
              }

              return (
                <Text key={index} type={statusType}>
                  {progress.resultDesc}
                </Text>
              );
            })}
          </div>
        );
      }

      // 只有在没有进度信息时，才检查 isTaskFinished
      if (status.taskStatus === 1 && status.isTaskFinished && !status.progresses?.length) {
        return '等待开始执行';
      }

      // 根据不同步骤显示对应的状态信息
      if (step === 0) {
        // 如果是初始状态且没有任务状态，显示预设置提示
        if (!status.taskStatus) {
          return gridCurrentMode === 'true' ? '请进行并网转离网预设置' : '请进行离网转并网预设置';
        }

        // 预设置步骤
        switch (status.taskStatus) {
          case 1:
            return '预设置完成，请执行下一步';
          case 2:
            return '正在执行预设置...';
          case 3:
            return '等待执行预设置...';
          case 0:
            return `预设置失败: ${status.errorMsg || '未知错误'}`;
          default:
            return '等待开始预设置';
        }
      } else if (step === 1) {
        // 并网转离网/离网转并网步骤
        switch (status.taskStatus) {
          case 1:
            return status.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID
              ? '并网转离网完成，请执行下一步'
              : '离网转并网完成，请执行下一步';
          case 2:
            return status.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID
              ? '正在执行并网转离网...'
              : '正在执行离网转并网...';
          case 3:
            return status.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID
              ? '等待执行并网转离网...'
              : '等待执行离网转并网...';
          case 0:
            return `执行失败: ${status.errorMsg || '未知错误'}`;
          default:
            return '等待开始执行';
        }
      } else if (step === 2) {
        // 完成步骤
        switch (status.taskStatus) {
          case 1:
            return '操作已完成';
          case 2:
            return status.ctrlCmd === GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY
              ? '正在执行运行离网策略...'
              : '正在执行运行并网策略...';
          case 3:
            return status.ctrlCmd === GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY
              ? '等待执行运行离网策略...'
              : '等待执行运行并网策略...';
          case 0:
            return `执行失败: ${status.errorMsg || '未知错误'}`;
          default:
            return '等待执行最后一步';
        }
      }

      return '当前状态: 未进行并离网操作';
    };

    return (
      <div className={styles.stepStatusWrapper}>
        <div className={styles.stepStatusDisplay}>
          {loading && (
            <div className={styles.loadingContainer}>
              <Spin />
            </div>
          )}
          <div className={styles.statusContent}>
            <div className={styles.currentStatus}>{getStepStatusDescription()}</div>
            {status?.errorMsg && (
              <div className={styles.errorMessage}>
                <Text type="danger">错误信息: {status.errorMsg}</Text>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  // 修改检查错误状态的函数
  const checkErrorStatus = (status: CtrlStatus | null) => {
    // 只要 taskStatus 为 0 就认为是错误状态
    return status?.taskStatus === 0;
  };

  // 添加重新开始的确认弹窗
  const showRestartConfirm = () => {
    return new Promise((resolve) => {
      Modal.confirm({
        title: '操作失败',
        content: '当前步骤执行失败，是否重新开始？',
        okText: '重新开始',
        cancelText: '取消',
        onOk: async () => {
          await resetState(false); // 传入 false 表示是重新开始
          resolve(true);
        },
        onCancel: () => {
          resolve(false);
        },
      });
    });
  };

  // 并网模式的步骤表单
  const GridModeSteps = () => (
    <StepsForm
      key={currentStep}
      current={currentStep}
      formRef={stepFormRef}
      onFinish={async () => {
        message.success('并网转离网操作完成');
        await resetState(true);
        return true;
      }}
      stepsProps={{
        style: {
          minHeight: '36px',
        },
      }}
      submitter={{
        render: (props) => {
          if (props.step === 0 || props.step === 1) {
            return (
              <Button
                type="primary"
                onClick={async () => {
                  // 检查错误状态
                  if (checkErrorStatus(ctrlStatus)) {
                    const shouldRestart = await showRestartConfirm();
                    if (shouldRestart) {
                      // 如果用户确认重新开始，不触发 onSubmit
                      return;
                    }
                    // 如果用户取消，停留在当前步骤
                    return;
                  }
                  // 如果没有错误，正常执行下一步
                  props.onSubmit?.();
                }}
              >
                下一步
              </Button>
            );
          }
          return (
            <Button
              type="primary"
              onClick={async () => {
                if (checkErrorStatus(ctrlStatus)) {
                  const shouldRestart = await showRestartConfirm();
                  if (shouldRestart) {
                    return;
                  }
                  return;
                }
                props.onSubmit?.();
              }}
            >
              完成
            </Button>
          );
        },
      }}
    >
      <StepsForm.StepForm
        name="gridStep1"
        title="预设置"
        onFinish={async () => {
          // 检查是否存在错误状态
          if (checkErrorStatus(ctrlStatus)) {
            const shouldRestart = await showRestartConfirm();
            if (shouldRestart) {
              return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET);
            }
            return false;
          }
          return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET);
        }}
      >
        <div className={styles.manualControlWrapper}>
          <div className={styles.gridSwitchTips}>
            <Popover placement="bottom" content={manualControlTip} trigger="click">
              <a href="#" style={{ color: '#1A6CFE' }} className={styles.manualControl}>
                {gridMode === 'grid' ? '手动拉闸' : '手动合闸'} ⓘ
              </a>
            </Popover>
          </div>
        </div>
        {currentStep === 0 && <StatusDisplay status={ctrlStatus} loading={loading} step={1} />}
      </StepsForm.StepForm>

      <StepsForm.StepForm
        name="gridStep2"
        title={gridMode === 'grid' ? '并网转离网' : '离网转并网'}
        onFinish={async () => {
          // 检查是否存在错误状态
          if (checkErrorStatus(ctrlStatus)) {
            const shouldRestart = await showRestartConfirm();
            if (shouldRestart) {
              return handleStepFinishRef.current(
                gridMode === 'grid'
                  ? GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET
                  : GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET,
              );
            }
            return false;
          }

          // 并网转离网的逻辑
          if (gridMode === 'grid') {
            if (ctrlStatus?.taskStatus === 1) {
              if (ctrlStatus.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID_PRESET) {
                // 预设置完成，执行并网转离网
                return new Promise((resolve) => {
                  Modal.confirm({
                    title: '确认操作',
                    content: '手动断开并网点开关刀闸',
                    okText: '已断开',
                    cancelText: '取消',
                    onOk: async () => {
                      const result = await handleStepFinishRef.current(
                        GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID,
                        true,
                      );
                      resolve(result);
                    },
                    onCancel: () => {
                      resolve(false);
                    },
                  });
                });
              } else if (ctrlStatus.ctrlCmd === GRID_CONTROL_COMMANDS.GRID_TO_OFF_GRID) {
                // 并网转离网已完成，执行运行离网策略
                return new Promise((resolve) => {
                  Modal.confirm({
                    title: '确认执行运行离网策略',
                    content: '并网转离网已完成，是否立即执行运行离网策略？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: async () => {
                      const result = await handleStepFinishRef.current(
                        GRID_CONTROL_COMMANDS.RUN_OFF_GRID_STRATEGY,
                        false,
                      );
                      resolve(result);
                    },
                    onCancel: () => {
                      resolve(false);
                    },
                  });
                });
              }
            }
            // 如果状态不符合预期，提示错误
            message.error('请先完成并网转离网预设置操作');
            return false;
          } else {
            // 离网转并网的逻辑
            if (
              !(
                ctrlStatus?.taskStatus === 1 &&
                ctrlStatus?.ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET
              )
            ) {
              message.error('请先完成离网转并网预设置操作');
              return false;
            }
            return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID, true);
          }
        }}
      >
        <div className={styles.manualControlWrapper}>
          <div className={styles.gridSwitchTips}>
            <Popover placement="bottom" content={manualControlTip} trigger="click">
              <a href="#" style={{ color: '#1A6CFE' }} className={styles.manualControl}>
                {gridMode === 'grid' ? '手动拉闸' : '手动合闸'} ⓘ
              </a>
            </Popover>
          </div>
        </div>
        {currentStep === 1 && <StatusDisplay status={ctrlStatus} loading={loading} step={2} />}
      </StepsForm.StepForm>

      <StepsForm.StepForm name="gridStep3" title="完成">
        {currentStep === 2 && (
          <div className={styles.gridSwitchStatus}>
            <StatusDisplay status={ctrlStatus} loading={loading} step={3} />
          </div>
        )}
      </StepsForm.StepForm>
    </StepsForm>
  );

  // 离网模式的步骤表单
  const OffGridModeSteps = () => (
    <StepsForm
      key={currentStep}
      current={currentStep}
      formRef={stepFormRef}
      onFinish={async () => {
        message.success('离网转并网操作完成');
        await resetState(true);
        return true;
      }}
      stepsProps={{
        style: {
          minHeight: '36px',
        },
      }}
      submitter={{
        render: (props) => {
          if (props.step === 0 || props.step === 1) {
            return (
              <Button
                type="primary"
                onClick={async () => {
                  if (checkErrorStatus(ctrlStatus)) {
                    const shouldRestart = await showRestartConfirm();
                    if (shouldRestart) {
                      return;
                    }
                    return;
                  }
                  props.onSubmit?.();
                }}
              >
                下一步
              </Button>
            );
          }
          return (
            <Button
              type="primary"
              onClick={async () => {
                if (checkErrorStatus(ctrlStatus)) {
                  const shouldRestart = await showRestartConfirm();
                  if (shouldRestart) {
                    return;
                  }
                  return;
                }
                props.onSubmit?.();
              }}
            >
              完成
            </Button>
          );
        },
      }}
    >
      <StepsForm.StepForm
        name="offGridStep1"
        title="预设置"
        onFinish={async () => {
          if (checkErrorStatus(ctrlStatus)) {
            const shouldRestart = await showRestartConfirm();
            if (shouldRestart) {
              return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET);
            }
            return false;
          }
          return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET);
        }}
      >
        <div className={styles.manualControlWrapper}>
          <div className={styles.gridSwitchTips}>
            <Popover placement="bottom" content={manualControlTip} trigger="click">
              <a href="#" style={{ color: '#1A6CFE' }} className={styles.manualControl}>
                {gridMode === 'grid' ? '手动拉闸' : '手动合闸'} ⓘ
              </a>
            </Popover>
          </div>
        </div>
        {currentStep === 0 && <StatusDisplay status={ctrlStatus} loading={loading} step={1} />}
      </StepsForm.StepForm>

      <StepsForm.StepForm
        name="offGridStep2"
        title="离网转并网"
        onFinish={async () => {
          if (checkErrorStatus(ctrlStatus)) {
            const shouldRestart = await showRestartConfirm();
            if (shouldRestart) {
              return handleStepFinishRef.current(GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET);
            }
            return false;
          }

          // 检查当前状态
          if (ctrlStatus?.taskStatus === 1) {
            if (ctrlStatus.ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID_PRESET) {
              // 预设置完成，执行离网转并网
              return new Promise((resolve) => {
                Modal.confirm({
                  title: '确认操作',
                  content: '手动闭合并网点开关刀闸',
                  okText: '已闭合',
                  cancelText: '取消',
                  onOk: async () => {
                    const result = await handleStepFinishRef.current(
                      GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID,
                      true,
                    );
                    resolve(result);
                  },
                  onCancel: () => {
                    resolve(false);
                  },
                });
              });
            } else if (ctrlStatus.ctrlCmd === GRID_CONTROL_COMMANDS.OFF_GRID_TO_GRID) {
              // 离网转并网已完成，执行运行并网策略
              return new Promise((resolve) => {
                Modal.confirm({
                  title: '确认执行运行并网策略',
                  content: '离网转并网已完成，是否立即执行运行并网策略？',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    const result = await handleStepFinishRef.current(
                      GRID_CONTROL_COMMANDS.RUN_GRID_STRATEGY,
                      false,
                    );
                    resolve(result);
                  },
                  onCancel: () => {
                    resolve(false);
                  },
                });
              });
            }
          }

          // 如果状态不符合预期，提示错误
          message.error('请先完成离网转并网预设置操作');
          return false;
        }}
      >
        <div className={styles.manualControlWrapper}>
          <div className={styles.gridSwitchTips}>
            <Popover placement="bottom" content={manualControlTip} trigger="click">
              <a href="#" style={{ color: '#1A6CFE' }} className={styles.manualControl}>
                {gridMode === 'grid' ? '手动拉闸' : '手动合闸'} ⓘ
              </a>
            </Popover>
          </div>
        </div>
        {currentStep === 1 && <StatusDisplay status={ctrlStatus} loading={loading} step={2} />}
      </StepsForm.StepForm>

      <StepsForm.StepForm name="offGridStep3" title="完成">
        {currentStep === 2 && (
          <div className={styles.gridSwitchStatus}>
            <StatusDisplay status={ctrlStatus} loading={loading} step={3} />
          </div>
        )}
      </StepsForm.StepForm>
    </StepsForm>
  );

  return (
    <>
      <div className={styles.gridSwitchContainer}>
        <div style={{ marginBottom: 24 }}>
          <span style={{ marginRight: 8 }}>并离网运行状态</span>
          <Tag color={gridCurrentMode === 'true' ? 'blue' : 'orange'}>
            {gridCurrentMode === 'true' ? '并网' : '离网'}
          </Tag>
        </div>

        <div style={{ marginBottom: 24 }}>
          <span style={{ marginRight: 8 }}>切换并离网</span>
          <Radio.Group onChange={handleModeChange} value={gridMode}>
            <Radio value="grid" disabled={gridCurrentMode === 'false'}>
              并网转离网
            </Radio>
            <Radio value="offGrid" disabled={gridCurrentMode === 'true'}>
              离网转并网
            </Radio>
          </Radio.Group>
        </div>
        {gridMode === 'grid' ? <GridModeSteps /> : <OffGridModeSteps />}
      </div>

      <ModalForm
        title="预设置操作验证"
        open={smsModalVisible}
        onOpenChange={setSmsModalVisible}
        onFinish={handleSmsVerify}
        modalProps={{ destroyOnClose: true }}
        width={420}
      >
        <Flex vertical align="center" flex={1}>
          <p>确认当前{gridCurrentMode === 'true' ? '并网' : '离网'}状态正确！！！</p>
          <p>执行{gridCurrentMode === 'true' ? '并网转离网' : '离网转并网'}设置操作需要短信验证</p>
          <ProForm.Group>
            <ProFormCaptcha
              fieldProps={{
                size: 'middle',
                prefix: <MailTwoTone />,
              }}
              captchaProps={{
                size: 'middle',
                style: { width: 100, fontSize: 12 },
              }}
              name="smsCode"
              rules={[
                {
                  required: true,
                  message: '请输入验证码',
                },
              ]}
              placeholder="请输入验证码"
              onGetCaptcha={handleGetCaptcha}
            />
          </ProForm.Group>
        </Flex>
      </ModalForm>
    </>
  );
};

export default GridSwitch;
